from flask import Blueprint, request, jsonify
from app.services.review_plan_service import ReviewPlanService
from app.services.study_record_service import StudyRecordService
from app.services.task_service import TaskService
from app.extensions import db

bp = Blueprint('study', __name__)

# 认识
@bp.route('/know', methods=['POST'])
def know():
    data = request.get_json()
    # 打印数据
    print('know:==================================')
    # print(data)

    # 获取Data中的数据
    task_id = data.get('task_id')
    content_id = data.get('content_id')
    student_id = data.get('student_id')
    content_type = data.get('type', '字词')  # 默认值为'字词'
    duration = data.get('duration', 1)      # 默认1分钟
    mastery_score = data.get('mastery_score', 0)

    # 打印出以上数据
    # if task_id and content_id and student_id:
    #     print('task_id:', task_id)
    #     print('content_id:', content_id)
    #     print('student_id:', student_id)
    #     print('content_type:', content_type)
    #     print('duration:', duration)
    #     print('mastery_score:', mastery_score)

    try:
        # 开启事务
        db.session.begin()
        
        # 更新review_plan表
        next_review_date=ReviewPlanService.update_review_plan_byKnow(student_id,content_id)
        # 更新学习记录表
        StudyRecordService.update_study_record_byKnow(student_id,content_id,content_type,duration,mastery_score)
        # 更新task表
        TaskService.update_task_byKnow(task_id,next_review_date,student_id,content_id)
        
        # 提交事务
        db.session.commit()
        
        return jsonify({
                'success': True,
                'message': 'Learning record saved successfully',
            }), 200
            
    except Exception as e:
        # 发生错误时回滚事务
        db.session.rollback()
        print(f"Error in /know endpoint: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'An error occurred: {str(e)}'
        }), 500
# 熟悉
# 模糊
# 忘记
# 不认识